package org.jbelis.yodaquotes.server;

import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jbelis.yodaquotes.Quote;
import org.jbelis.yodaquotes.store.QuoteStore;
import org.jbelis.yodaquotes.store.jdo.JDOQuoteStore;

@SuppressWarnings("serial")
public class SubmitQuoteService extends HttpServlet {

	private QuoteStore store = new JDOQuoteStore();
	
	@Override
	public final void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		process(request, response);
	}

	@Override
	public final void doGet(HttpServletRequest request,
			HttpServletResponse response) {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		String text = request.getParameter("text");
		String context = request.getParameter("context");
		String author = request.getParameter("author");

		Quote quote = submitQuote(text, author, context);

		try {
			quote.write(response.getWriter());
		} catch (Exception e) {

		}
	}

	public Quote submitQuote(String text, String author, String context) {
		
		List<Quote> quotes = store.findByText(text);
		if (!quotes.isEmpty())
			return quotes.get(0);

		Quote quote = new Quote(text, author, context);

		return store.store(quote);
	}
}
